"""手机播放列表页面处理器模块"""

import json
from typing import Optional, Dict, Any
from aiohttp import web
from dashboard.data_manager import DataManager
from embytools.emby_client import EmbyClient

router = web.RouteTableDef()

# Emby客户端实例，将在main.py中注入
emby_client: Optional[EmbyClient] = None

# 数据管理器实例，将在main.py中注入
data_manager: Optional[DataManager] = None


def set_data_manager(manager: DataManager):
    """设置数据管理器实例"""
    global data_manager
    data_manager = manager


def get_enabled_libraries():
    """获取已启用的媒体库列表"""
    return data_manager.get_enabled_libraries()


def set_library_enabled(library_id, enabled):
    """设置媒体库启用状态"""
    data_manager.set_library_enabled(library_id, enabled)


def set_emby_client(client: EmbyClient):
    """设置Emby客户端实例"""
    global emby_client
    emby_client = client


@router.get("/phone-playlists")
async def phone_playlists_handler(request: web.Request):
    """手机播放列表页面"""
    html_content = '''
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>手机播放列表管理 - EmbyTools</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            body {
                font-family: Arial, sans-serif;
                background-color: #f5f5f5;
                color: #333;
            }
            .navbar {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                padding: 1rem 2rem;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }
            .nav-container {
                max-width: 1200px;
                margin: 0 auto;
                display: flex;
                flex-direction: column;
                align-items: center;
            }
            
            /* 桌面端样式 */
            @media (min-width: 768px) {
                .nav-container {
                    flex-direction: row;
                    justify-content: space-between;
                }
            }
            .nav-title {
                color: white;
                font-size: 1.5rem;
                font-weight: bold;
                font-family: 'BM HANNA Pro OTF', sans-serif;
            }
            .nav-links {
                display: flex;
                gap: 2rem;
            }
            .nav-link {
                color: white;
                text-decoration: none;
                padding: 0.5rem 1rem;
                border-radius: 5px;
                transition: background-color 0.3s;
            }
            .nav-link:hover, .nav-link.active {
                background-color: rgba(255,255,255,0.2);
            }
            .container {
                max-width: 1200px;
                margin: 2rem auto;
                padding: 0 2rem;
            }
            .page-title {
                text-align: center;
                margin-bottom: 2rem;
                color: #333;
            }
            .server-info {
                background: #e3f2fd;
                padding: 1rem;
                border-radius: 8px;
                margin-bottom: 2rem;
                text-align: center;
            }
            .libraries-grid {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
                gap: 1.5rem;
            }
            .library-card {
                background: transparent;
                border: 1px solid rgba(255, 255, 255, 0.3);
                border-radius: 15px;
                padding: 0;
                box-shadow: 0 4px 15px rgba(0,0,0,0.2);
                transition: transform 0.3s, box-shadow 0.3s;
                position: relative;
                overflow: hidden;
                aspect-ratio: 16 / 9;
                min-height: 200px;
                display: flex;
                flex-direction: column;
                justify-content: flex-start;
            }
            .library-card.with-cover::before {
                content: '';
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-image: var(--cover-url);
                background-size: cover;
                background-position: center;
                background-repeat: no-repeat;
                z-index: 1;
            }
            .library-card-content {
                position: relative;
                z-index: 2;
                height: 100%;
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                padding: 1rem;
            }
            .library-name {
                font-size: 1.5rem;
                font-weight: bold;
                color: var(--text-color, white);
                text-shadow: var(--text-shadow, 2px 2px 4px rgba(0, 0, 0, 0.7));
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 1rem;
                border-radius: 8px;
                background: transparent;
                margin: -1rem -1rem 1rem -1rem;
            }
            .library-card:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 15px rgba(0,0,0,0.15);
            }
            .library-type {
                display: inline-block;
                padding: 0.15rem 0.4rem;
                border-radius: 10px;
                font-size: 0.6rem;
                font-weight: bold;
                text-transform: uppercase;
                letter-spacing: 0.3px;
                margin-left: 0.5rem;
                box-shadow: 0 1px 4px rgba(0,0,0,0.3);
                border: 1px solid rgba(255,255,255,0.3);
                backdrop-filter: blur(10px);
            }
            
            .library-type.movies {
                background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
                color: white;
                text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            }
            
            .library-type.music {
                background: linear-gradient(135deg, #48cae4 0%, #0096c7 100%);
                color: white;
                text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            }
            
            .library-type.homevideos {
                background: linear-gradient(135deg, #9b5de5 0%, #7209b7 100%);
                color: white;
                text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            }
            
            .library-type.playlists {
                background: linear-gradient(135deg, #f9c74f 0%, #f8961e 100%);
                color: white;
                text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            }
            
            .library-type.boxsets {
                background: linear-gradient(135deg, #90be6d 0%, #43aa8b 100%);
                color: white;
                text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            }
            
            .library-type.default {
                background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
                color: white;
                text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            }
            .library-action-btn {
                padding: 0.4rem 0.75rem;
                border: none;
                border-radius: 15px;
                font-size: 0.7rem;
                font-weight: bold;
                cursor: pointer;
                transition: all 0.3s ease;
                box-shadow: 0 2px 5px rgba(0,0,0,0.2);
                border: 1px solid rgba(255,255,255,0.3);
                backdrop-filter: blur(5px);
            }
            .library-action-btn.enabled {
                background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
                color: white;
                text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            }
            .library-action-btn.disabled {
                background: linear-gradient(135deg, #48cae4 0%, #0096c7 100%);
                color: white;
                text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
            }
            .library-action-btn:hover {
                transform: scale(1.05);
                box-shadow: 0 3px 8px rgba(0,0,0,0.3);
            }
            .loading {
                text-align: center;
                padding: 3rem;
                color: #666;
            }
            .error {
                background-color: #ffebee;
                color: #c62828;
                padding: 1.5rem;
                border-radius: 5px;
                text-align: center;
                margin: 1rem 0;
            }
            .success {
                background-color: #e8f5e9;
                color: #2e7d32;
                padding: 1rem;
                border-radius: 5px;
                text-align: center;
                margin: 1rem 0;
            }
            .hidden {
                display: none;
            }
        </style>
    </head>
    <body>
        <nav class="navbar">
            <div class="nav-container">
                <div class="nav-title">Mocaca</div>
                <div class="nav-links">
                    <a href="/" class="nav-link">媒体库</a>
                    <a href="/phone-playlists" class="nav-link active">播放列表</a>
                    <a href="/douyin-sources" class="nav-link">数据源</a>
                    <a href="/settings" class="nav-link">设置</a>
                </div>
            </div>
        </nav>

        <div class="container">
            <h1 class="page-title">为媒体库增加手机播放列表</h1>
            
            <div class="server-info">
                <strong>功能说明:</strong> 为选中的媒体库创建手机播放列表，自动筛选竖屏视频（宽小于高）
            </div>

            <div id="phone-libraries-container">
                <div class="loading">正在加载媒体库列表...</div>
            </div>
            
            <div id="phone-result" class="hidden"></div>
        </div>

        <script>
            let libraries = [];

            // 页面加载完成后初始化
            document.addEventListener('DOMContentLoaded', async function() {
                await loadLibraries();
                await displayPhoneLibraries();
            });

            // 加载媒体库列表
            async function loadLibraries() {
                try {
                    const response = await fetch('/api/libraries');
                    const data = await response.json();
                    
                    if (data.success) {
                        libraries = data.libraries;
                    } else {
                        console.error('加载媒体库失败:', data.error);
                    }
                } catch (error) {
                    console.error('加载媒体库出错:', error);
                }
            }

            // 显示手机播放列表页面的媒体库
            async function displayPhoneLibraries() {
                try {
                    const container = document.getElementById('phone-libraries-container');
                    
                    if (libraries.length === 0) {
                        container.innerHTML = '<div class="error">未找到媒体库</div>';
                        return;
                    }
                    
                    // 获取已启用的媒体库信息
                    const enabledResponse = await fetch('/api/enabled-libraries');
                    const enabledData = await enabledResponse.json();
                    const enabledLibraryIds = enabledData.success ? enabledData.enabled_libraries : [];
                    
                    const librariesHtml = libraries.map(lib => {
                        const isEnabled = enabledLibraryIds.includes(lib.id);
                        const hasCover = lib.cover_url;
                        const coverStyle = hasCover ? `--cover-url: url('${lib.cover_url}');` : '';
                        const cardClass = hasCover ? 'library-card with-cover' : 'library-card';
                        
                        // 计算文字颜色 - 如果有封面则自适应，否则使用默认颜色
                        const textColor = hasCover ? 'white' : '#2c3e50';
                        const textShadow = hasCover ? '2px 2px 4px rgba(0, 0, 0, 0.7)' : 'none';
                        
                        const textStyle = hasCover ? 
                            `--text-color: ${textColor}; --text-shadow: ${textShadow};` : 
                            '';
                        
                        return `
                        <div class="${cardClass}" data-lib-id="${lib.id}" style="${coverStyle} ${textStyle}">
                            <div class="library-card-content">
                                <div class="library-name">
                                    ${lib.name}
                                    <span class="library-type ${lib.type || 'default'}">${lib.type || 'default'}</span>
                                </div>
                                <div style="position: absolute; bottom: 1rem; right: 1rem;">
                                    <button class="library-action-btn ${isEnabled ? 'enabled' : 'disabled'}"
                                            onclick="togglePlaylistStatus('${lib.id}', '${lib.name}', ${isEnabled})">
                                        ${isEnabled ? '关闭' : '启用'}
                                    </button>
                                </div>
                            </div>
                        </div>
                    `}).join('');
                    
                    container.innerHTML = `
                        <h2>媒体库列表 (${libraries.length}个)</h2>
                        <div class="libraries-grid">${librariesHtml}</div>
                    `;
                } catch (error) {
                    document.getElementById('phone-libraries-container').innerHTML = 
                        `<div class="error">加载失败: ${error.message}</div>`;
                }
            }
            
            // 切换播放列表状态（启用/禁用并创建/删除）
            async function togglePlaylistStatus(libraryId, libraryName, isEnabled) {
                try {
                    const resultElement = document.getElementById('phone-result');
                    resultElement.innerHTML = `<div class="loading">正在${isEnabled ? '关闭' : '启用'}手机播放列表...</div>`;
                    resultElement.classList.remove('hidden', 'error', 'success');
                    
                    // 1. 先更新启用状态
                    const toggleResponse = await fetch('/api/toggle-library-enabled', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            library_id: libraryId,
                            enabled: !isEnabled
                        })
                    });
                    
                    const toggleData = await toggleResponse.json();
                    if (!toggleData.success) {
                        throw new Error('更新启用状态失败');
                    }
                    
                    // 2. 如果是启用，则创建播放列表
                    if (!isEnabled) {
                        const createResponse = await fetch('/api/create-phone-playlist', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({
                                library_id: libraryId,
                                library_name: libraryName
                            })
                        });
                        
                        const createData = await createResponse.json();
                        
                        if (createData.success) {
                            resultElement.innerHTML = `<div class="success">播放列表启用成功: ${createData.playlist_name}</div>`;
                            resultElement.classList.add('success');
                        } else {
                            // 如果创建失败，恢复启用状态
                            await fetch('/api/toggle-library-enabled', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({
                                    library_id: libraryId,
                                    enabled: false
                                })
                            });
                            throw new Error(`创建播放列表失败: ${createData.error}`);
                        }
                    } else {
                        // 禁用时只需要更新状态
                        resultElement.innerHTML = '<div class="success">播放列表已关闭</div>';
                        resultElement.classList.add('success');
                    }
                    
                    // 3. 更新按钮状态
                    const btn = document.querySelector(`.library-card[data-lib-id="${libraryId}"] .library-action-btn`);
                    if (btn) {
                        btn.textContent = isEnabled ? '启用' : '关闭';
                        btn.classList.toggle('enabled', !isEnabled);
                        btn.classList.toggle('disabled', isEnabled);
                        btn.setAttribute('onclick', `togglePlaylistStatus('${libraryId}', '${libraryName}', ${!isEnabled})`);
                    }
                    
                    // 显示结果3秒后隐藏
                    setTimeout(() => {
                        resultElement.classList.add('hidden');
                    }, 3000);
                } catch (error) {
                    console.error('操作出错:', error);
                    document.getElementById('phone-result').innerHTML = 
                        `<div class="error">操作失败: ${error.message}</div>`;
                    document.getElementById('phone-result').classList.remove('hidden', 'success');
                    document.getElementById('phone-result').classList.add('error');
                }
            }
        </script>
    </body>
    </html>
    '''
    
    return web.Response(text=html_content, content_type='text/html', charset='utf-8')


@router.post("/api/toggle-library-enabled")
async def toggle_library_enabled_handler(request: web.Request):
    """切换媒体库启用状态"""
    try:
        data = await request.json()
        library_id = data.get('library_id')
        enabled = data.get('enabled', False)
        
        if not library_id:
            return web.json_response({
                'success': False,
                'error': '缺少媒体库ID'
            }, status=400)
        
        # 设置媒体库启用状态
        set_library_enabled(library_id, enabled)
        
        return web.json_response({
            'success': True,
            'message': f'媒体库{"启用" if enabled else "禁用"}成功'
        })
    except Exception as e:
        return web.json_response({
            'success': False,
            'error': str(e)
        }, status=500)


@router.get("/api/enabled-libraries")
async def get_enabled_libraries_handler(request: web.Request):
    """获取已启用的媒体库列表"""
    try:
        enabled_libraries = get_enabled_libraries()
        
        return web.json_response({
            'success': True,
            'enabled_libraries': enabled_libraries
        })
    except Exception as e:
        return web.json_response({
            'success': False,
            'error': str(e)
        }, status=500)


@router.post("/api/create-phone-playlist")
async def create_phone_playlist_handler(request: web.Request):
    """创建手机播放列表"""
    try:
        global emby_client
        
        if not emby_client:
            return web.json_response({
                'success': False,
                'error': 'Emby客户端未初始化'
            }, status=500)
        
        data = await request.json()
        library_id = data.get('library_id')
        library_name = data.get('library_name')
        
        if not library_id or not library_name:
            return web.json_response({
                'success': False,
                'error': '缺少媒体库ID或名称'
            }, status=400)
        
        # 获取媒体库中的所有项目
        items = emby_client.get_library_items(library_id)
        
        # 过滤竖屏视频（宽度小于高度）
        portrait_items = []
        skipped_count = 0
        
        for item in items:
            # 检查是否有宽高信息，并且是竖屏
            if item.get('Width') and item.get('Height') and item['Width'] < item['Height']:
                portrait_items.append(item['Id'])
            else:
                skipped_count += 1
        
        # 创建播放列表
        playlist_name = f"{library_name} - 手机播放列表"
        playlist_id = emby_client.create_playlist(playlist_name, portrait_items)
        
        return web.json_response({
            'success': True,
            'playlist_id': playlist_id,
            'playlist_name': playlist_name,
            'added_count': len(portrait_items),
            'skipped_count': skipped_count
        })
    except Exception as e:
        return web.json_response({
            'success': False,
            'error': str(e)
        }, status=500)


def set_emby_client(client: EmbyClient):
    """设置Emby客户端实例"""
    global emby_client
    emby_client = client